//go:build !prod
// +build !prod

package router

import (
	"bytes"
	"github.com/labstack/echo/v4"
	logs "github.com/sirupsen/logrus"
	"sync"
	"time"
	"turingApi/conf"
)

const AppJsUrl = "/static/js/app.js"
const AppCssUrl = "/static/css/app.css"

var pool *sync.Pool

func init() {
	logs.SetLevel(logs.DebugLevel)
	logs.SetReportCaller(true)
	pool = &sync.Pool{
		New: func() interface{} {
			return bytes.NewBuffer(make([]byte, 512))
		},
	}
}

// midLogger 中间件-日志记录
func midLogger(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) (err error) {
		start := time.Now()
		if err = next(ctx); err != nil {
			ctx.Error(err)
		}
		stop := time.Now()
		buf := pool.Get().(*bytes.Buffer)
		buf.Reset()
		defer pool.Put(buf)
		buf.WriteString("\t" + ctx.RealIP())
		buf.WriteString("\t" + ctx.Request().Method + "：" + ctx.Request().RequestURI)
		buf.WriteString(" - " + stop.Sub(start).String())
		// 这里仅仅记录的是 url 访问记录
		// 开发模式直接输出
		// 生产模式中间层会记录
		// os.Stdout.Write(buf.Bytes())
		logs.Debug(buf.String())
		return
	}
}

func zapLogger(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) (err error) {
		start := time.Now()
		var errMsg string
		if err = next(ctx); err != nil {
			errMsg = err.Error()
			ctx.Error(err)
		}
		stop := time.Now()
		buf := pool.Get().(*bytes.Buffer)
		buf.Reset()
		defer pool.Put(buf)
		buf.WriteString("    remote_ip: " + ctx.RealIP())
		buf.WriteString("    method: " + ctx.Request().Method + "=>" + ctx.Request().RequestURI)
		if len(errMsg) > 0 {
			buf.WriteString("    message: " + errMsg)
		}
		buf.WriteString(" - " + stop.Sub(start).String())

		// 这里仅仅记录的是 url 访问记录
		// 开发模式直接输出
		// 生产模式中间层会记录
		// os.Stdout.Write(buf.Bytes())
		//logs.Debug(buf.String())
		conf.Logger.Debug(buf.String())
		return
	}
}
